# import ldap
from tools.models import LdapBaseConf
from ..serializers import LdapConfSrializer


class AuthBaseLdap:
    def __init__(self, username=None, password=None):
        self.username = username
        self.password = password

    def GetLdapInfo(self):
        ldapInfo = LdapBaseConf.objects.all().first()
        serializer = LdapConfSrializer(ldapInfo)
        return serializer.data

    def ConnectLdap(self, host, port, dn, passwd):

        admin_dn = dn
        admin_passwd = passwd
        LdapConnect = ldap.initialize(f"ldap://{host}:{port}")
        LdapConnect.protocol_version = ldap.VERSION3
        try:
            result = LdapConnect.simple_bind_s(admin_dn, admin_passwd)
        except ConnectionError as e:
            return {'status': f'{e}'}
        else:
            if result[0] == 97:
                return {'status': 'success'}

    def hash_code(self):

        # md5，sha加密
        import hashlib, base64, binascii

        md5String = hashlib.md5(self.password.encode('utf-8')).hexdigest()
        binasciiString = binascii.a2b_hex(md5String)
        base64String = base64.b64encode(binasciiString).decode("utf-8")
        md5_pass = "{MD5}" + base64String

        shaString = hashlib.sha1(self.password.encode("utf-8")).hexdigest()
        shaBinasciiString = binascii.a2b_hex(shaString)
        shaBase64String = base64.b64encode(shaBinasciiString).decode("utf-8")
        sha_pass = "{SHA}" + shaBase64String

        passwd_pool = [passwd for passwd in (self.password, md5_pass, sha_pass)]

        return passwd_pool

    def BaseUserAuth(self):
        # 验证ldap用户信息
        ldapConfData = self.GetLdapInfo()
        LdapConnect = ldap.initialize(f"ldap://{ldapConfData['host']}:{ldapConfData['port']}")
        LdapConnect.protocol_version = ldap.VERSION3
        try:
            result = LdapConnect.simple_bind_s(ldapConfData['admin_dn'], ldapConfData['admin_password'])
        except ConnectionError as e:
            raise e
        else:
            if result[0] != 97:
                return {'status': 'failed', 'msg': 'ldap连接失败!'}

        searchScope = ldap.SCOPE_SUBTREE
        searchFilter = f"{ldapConfData['search_filter']}={self.username}"
        base_dn = ldapConfData['scbase']

        response = LdapConnect.search_s(base_dn, searchScope, searchFilter, None)
        attr_dict = response[0][1]
        user_sn = attr_dict['sn'][0].decode()
        user_name = attr_dict['cn'][0].decode()
        user_password = attr_dict['userPassword'][0].decode()
        password_pool = self.hash_code()

        if user_password in password_pool:
            return {'status': 'success', 'uid': user_name, 'sn': user_sn, 'msg': '登陆成功!'}
        else:
            return {'status': 'failed', 'uid': user_name, 'sn': user_sn, 'msg': '登陆失败!'}

